
#include "Header.h"
#include "SoundMath.h"

extern "C"
{
	DECLSPEC void STDCALL Common_Modulizer_LFO_Process(
		int length, int waveformBufferLength, double* ncurrentSample, double sync, double sync_position, double tempo
		, double* frequency, double* amplitude, double* amplitudeOffset
		, double* waveForm, double* output
		, double sampleRate)
	{
		sampleRate = 1.0 / sampleRate;
		double currentSample = *ncurrentSample;

		if (waveForm != nullptr)
		{
			// Sync off.
			if (sync == 0)
			{
				for (int i = 0; i < length; i++)
				{
					int index = (int)(++currentSample * frequency[i] * sampleRate * waveformBufferLength);
					output[i] = waveForm[index % waveformBufferLength] * amplitude[i] + amplitudeOffset[i];
				}
			}
			else
			{
				// Sync current sample.
				currentSample = sync_position;

				double syncValue = (double)sync * 0.001;
				double syncFreq = (tempo / 60) * sampleRate / syncValue;
				for (int i = 0; i < length; i++)
				{
					int index = (int)(++currentSample * syncFreq * waveformBufferLength);
					output[i] = waveForm[index % waveformBufferLength] * amplitude[i] + amplitudeOffset[i];
					++currentSample;
				}
			}
		}
		else
		{
			// Sinus.

			// Sync off.
			if (sync == 0)
			{
				for (int i = 0; i < length; i++)
				{
					output[i] = sin((2 * PI * ++currentSample * frequency[i]) * sampleRate) * amplitude[i] + amplitudeOffset[i];
				}
			}
			else
			{
				// Sync current sample.
				currentSample = sync_position;

				double syncValue = (double)sync * 0.001;
				double syncFreq = (tempo / 60) * sampleRate / syncValue;
				for (int i = 0; i < length; i++)
				{
					output[i] = sin((2 * PI * ++currentSample) * syncFreq) * amplitude[i] + amplitudeOffset[i];
				}
			}
		}

		(*ncurrentSample) = currentSample;
	}
}